package com.joe.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by joe on 2018/11/25
 */
public class StringUtils {

    private static final Pattern trimPattern = Pattern.compile("^[\\s\\p{Zs}]*(?<CONTENT>.*?)[\\s\\p{Zs}]*$");

    /**
     * 强力trim
     */
    public static String trim(String source) {
        Matcher matcher = trimPattern.matcher(source);

        if (matcher.find()) {
            return matcher.group("CONTENT");
        }
        return source;
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String source) {
        return source == null || source.isEmpty();
    }

    /**
     * 转化为下划线分割命名
     */
    public static String toUnderLineName(String source) {
        StringBuilder sb = new StringBuilder();
        char[] chars = source.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if (Character.isUpperCase(c) && i > 0) {
                sb.append("_");
                sb.append(Character.toLowerCase(c));
                continue;
            }
            sb.append(c);
        }
        return sb.toString();
    }

    /**
     * 转化为驼峰命名
     */
    public static String toCamelName(String source) {
        StringBuilder sb = new StringBuilder();
        char[] chars = source.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if ('_' == c) {
                c = chars[++i];
                sb.append(Character.toUpperCase(c));
                continue;
            }
            sb.append(c);
        }
        return sb.toString();
    }


}
